import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:sinosheets/main_config.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';
import 'package:sinosheets/utils/theme/style_utils.dart';

import 'gb_webview_controller.dart';

class GBWebView extends StatelessWidget {
  final String url;
  final String? userAgent;
  final Map<String, String>? headers;
  final bool showLoading;
  final bool transparentBackground;
  final bool cacheEnabled;
  final bool clearCache;
  final bool useHybridComposition;
  final bool offscreenPreRaster;
  final Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers;

  /// WebView创建完成回调
  final Function(InAppWebViewController controller)? onWebViewCreated;

  /// 页面开始加载回调
  final Function(InAppWebViewController controller, WebUri? url)? onLoadStart;

  /// 页面加载完成回调
  final Function(InAppWebViewController controller, WebUri? url)? onLoadStop;

  /// 页面加载出错回调
  final Function(InAppWebViewController controller, WebUri? url, int code, String message)? onLoadError;

  /// 进度变化回调
  final Function(InAppWebViewController controller, int progress)? onProgressChanged;

  /// 控制台消息回调
  final Function(InAppWebViewController controller, ConsoleMessage consoleMessage)? onConsoleMessage;

  /// URL拦截回调
  final Future<NavigationActionPolicy?> Function(InAppWebViewController controller, NavigationAction navigationAction)? shouldOverrideUrlLoading;

  /// 资源加载回调
  final Function(InAppWebViewController controller, LoadedResource resource)? onLoadResource;

  /// JavaScript处理器
  final Map<String, Function(List<dynamic> arguments)>? javaScriptHandlers;

  const GBWebView({
    Key? key,
    required this.url,
    this.userAgent,
    this.headers,
    this.showLoading = true,
    this.transparentBackground = false,
    this.cacheEnabled = true,
    this.clearCache = false,
    this.useHybridComposition = true,
    this.offscreenPreRaster = true,
    this.gestureRecognizers,
    this.onWebViewCreated,
    this.onLoadStart,
    this.onLoadStop,
    this.onLoadError,
    this.onProgressChanged,
    this.onConsoleMessage,
    this.shouldOverrideUrlLoading,
    this.onLoadResource,
    this.javaScriptHandlers,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(GBWebViewController(url), tag: url);

    return Container(
      color: ColorUtils.c_ffffff,
      child: InAppWebView(
        initialUrlRequest: URLRequest(
          url: WebUri(url),
          headers: headers,
        ),
        initialSettings: InAppWebViewSettings(
          transparentBackground: transparentBackground,
          cacheEnabled: cacheEnabled,
          clearCache: clearCache,
          mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
          useHybridComposition: useHybridComposition,
          offscreenPreRaster: offscreenPreRaster,
          mediaPlaybackRequiresUserGesture: false,
          useOnLoadResource: true,
          javaScriptEnabled: true,
          userAgent: userAgent,
        ),
        onWebViewCreated: (InAppWebViewController webViewController) {
          controller.webViewController = webViewController;

          // 注册JavaScript处理器
          if (javaScriptHandlers != null) {
            javaScriptHandlers!.forEach((handlerName, callback) {
              webViewController.addJavaScriptHandler(
                handlerName: handlerName,
                callback: callback,
              );
            });
          }

          onWebViewCreated?.call(webViewController);
        },
        shouldInterceptRequest: (_, request) async {
          return await controller.interceptRequest(request.url.toString());
        },
        shouldOverrideUrlLoading: (controller, navigationAction) async {
          if (shouldOverrideUrlLoading != null) {
            return await shouldOverrideUrlLoading!(controller, navigationAction);
          }

          final uri = navigationAction.request.url;
          if (uri == null) return NavigationActionPolicy.CANCEL;

          // 处理自定义scheme
          if (!uri.scheme.startsWith('http')) {
            LogUtil.d('拦截到自定义scheme: ${uri.toString()}');
            return NavigationActionPolicy.CANCEL;
          }

          return NavigationActionPolicy.ALLOW;
        },
        onLoadStart: (controller, url) {
          onLoadStart?.call(controller, url);
        },
        onLoadStop: (controller, url) {
          onLoadStop?.call(controller, url);
        },
        onConsoleMessage: (controller, consoleMessage) {
          LogUtil.d('WebView Console: ${consoleMessage.message}');
          onConsoleMessage?.call(controller, consoleMessage);
        },
        onReceivedServerTrustAuthRequest: (controller, challenge) async {
          return ServerTrustAuthResponse(action: ServerTrustAuthResponseAction.PROCEED);
        },
        onReceivedHttpError: (controller, request, errorResponse) {
          LogUtil.e('WebView HTTP错误: ${errorResponse.statusCode}');
        },
        onProgressChanged: (webViewController, progress) {
          controller.updateProgress(progress);
          onProgressChanged?.call(webViewController, progress);
        },
        onLoadResource: (webViewController, resource) async {
          String resourceUrl = resource.url.toString();
          if (resourceUrl.startsWith(AppPrefix.h5Prefix)) {
            await controller.handleResourceLoading(resource.url.toString());
          }
          onLoadResource?.call(webViewController, resource);
        },
        gestureRecognizers: gestureRecognizers,
      ),
    );
  }
}
